package com.platform.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * 配置文件读取工具类
 * 
 * @author LiangMingHui
 *
 */
public class PropertiesUtil {

	private final static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

	private static Properties prop;

	/**
	 * 加载配置文件
	 * 
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	static {
		String filePath = null;
		String configPath = System.getProperty("configPath");
		if (configPath == null) {
			filePath = PropertiesUtil.class.getClassLoader().getResource("config.properties").getPath();
		} else {
			filePath = configPath + "/" + "config.properties";
		}

		if (-1 != filePath.indexOf("%20")) {
			filePath = filePath.replaceAll("%20", " "); // 空格处理
		}

		prop = new Properties();
		InputStream is = null;
		try {
			is = new FileInputStream(new File(filePath));
			prop.load(is);
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(is);
		}

	}

	/**
	 * 根据KEY获取配置文件中对应的值
	 * 
	 * @param key
	 * @return
	 */
	public static String getValueByKey(String key) {
		return StringUtils.trim(prop.getProperty(key));
	}
}